﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace LitTools
{
    public class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
    {
        private static T _Instance;
        public static T Instance
        {
            get
            {
                if (_Instance == null)
                {
                    GameObject go = new GameObject(typeof(T).ToString());
                    DontDestroyOnLoad(go);
                    _Instance = go.AddComponent<T>();
                    _Instance.Init();
                }
                return _Instance;
            }
        }

        /// <summary>
        /// 私有化构造方法
        /// </summary>
        protected MonoSingleton()
        {

        }

        private void OnDestroy()
        {
            _Instance = null;
        }

        /// <summary>
        /// 初始化
        /// </summary>
        public virtual void Init()
        {
            //有需要重写此方法，进行单例初始化
            //此方法会在单例被创建时执行一次，不需要手动调用
        }

        /// <summary>
        /// 销毁
        /// </summary>
        public virtual void Dispose()
        {
            _Instance = null;
            Destroy(gameObject);
        }
    }
}